using Common.Net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Common.Tools
{
    public class TcpPack
    {
        byte[] data = new byte[1024];
        int startIndex = 0; //我们存取了多少字节数组的数据

        public byte[] Data
        {
            get { return data; }
        }

        public int StartIndex
        {
            get { return startIndex; }
        }

        public int RemainSize
        {
            get { return data.Length - startIndex; }
        }

        /// <summary>
        /// 解析数据
        /// </summary>
        /// <param name="newDataAmount"></param>
        /// <param name="processDataCallback"></param>
        public void ReceiveData(int newDataAmount, Action<RequestType, object> processDataCallback)
        {
            startIndex += newDataAmount;
            while (true)
            { //把4个字节，作为包头。如果小于4，包头都没有接受完。返回不解析
                if (startIndex <= 4)
                    return;
                //通过解析包头，知道数据包的长度
                int count = BitConverter.ToInt32(data, 0);
                //接受指定长度的数据
                if ((startIndex) >= count + 4)
                {
                    var msgInfo =
                        SerializeHelper.DeserializeFromBinary(data.Skip(4).ToArray(),typeof(MsgInfo)) as MsgInfo;
                    //找到对应的request,派发出去
                    processDataCallback(msgInfo.requestType, msgInfo.vo);
                    //把剩下的字节数组，留下来，下次使用
                    Array.Copy(data, count + 4, data, 0, startIndex - 4 - count);
                    startIndex -= (count + 4);
                }
                else
                {
                    break;
                }
            }
        }

        public static byte[] WriteData(MsgInfo info)
        {
            //转化成为二进制
            byte[] dataBytes = SerializeHelper.SerializeToBinary(info);
            int dataAmount = dataBytes.Length;
            //封包（包头+内容）
            byte[] dataAmountBytes = BitConverter.GetBytes(dataAmount);
            return dataAmountBytes.Concat(dataBytes).ToArray<byte>();
        }
    }
}
